package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.AddressEnum;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.pojo.ButtonPojo;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.dto.SignInSetDetailDTO;
import com.xbongbong.paas.pojo.vo.SignInSetVO;
import com.xbongbong.paas.service.PaasFormService;
import com.xbongbong.paas.service.SignInSetService;
import com.xbongbong.paas.service.dynamic.crm.strategy.CommunicateDynamicStrategy;
import com.xbongbong.paas.service.dynamic.crm.strategy.DynamicStrategyFactory;
import com.xbongbong.paas.service.log.crm.operation.SignInOperationLogHandle;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.GaodeGeoHelper;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.CommentUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.appdetail.pojo.dto.SignInDetailDTO;
import com.xbongbong.pro.appdetail.pojo.vo.SignInDetailVO;
import com.xbongbong.pro.applist.pojo.dto.SignInTrackDTO;
import com.xbongbong.pro.applist.pojo.vo.SignInListHeadVO;
import com.xbongbong.pro.applist.pojo.vo.SignInStatisticVO;
import com.xbongbong.pro.constant.RangeScreenConstant;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicSaveDTO;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.CustomerCommunicateErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SignInErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.log.pojo.dto.AddSignInDTO;
import com.xbongbong.pro.log.pojo.dto.DeleteSignInDTO;
import com.xbongbong.pro.message.constant.SignInPushConstant;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.help.PushHelper;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.pro.message.pojo.dto.MessageRabbitMqDTO;
import com.xbongbong.pro.rabbitmq.producer.BaseProducer;
import com.xbongbong.pro.service.toolbox.statistic.help.FiscalYearHelp;
import com.xbongbong.pro.statistic.pojo.FiscalYearTimePojo;
import com.xbongbong.pro.webexport.dto.SignInExportDTO;
import com.xbongbong.pro.webexport.vo.SignInExportVO;
import com.xbongbong.pro.weblist.pojo.NearCustomerPojo;
import com.xbongbong.pro.weblist.pojo.dto.NearCustomerDTO;
import com.xbongbong.pro.weblist.pojo.dto.SignInDTO;
import com.xbongbong.pro.weblist.pojo.dto.SignInDeleteDTO;
import com.xbongbong.pro.weblist.pojo.dto.SignInSaveDTO;
import com.xbongbong.pro.weblist.pojo.dto.SignInStatisticDTO;
import com.xbongbong.pro.weblist.pojo.vo.SignInListVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.SignInEntity;
import com.xbongbong.saas.domain.entity.SignInSetEntity;
import com.xbongbong.saas.domain.entity.ext.CustomerCommunicateEntityExt;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.domain.entity.ext.SignInEntityExt;
import com.xbongbong.saas.enums.ListGroupEnum;
import com.xbongbong.saas.enums.ListTopButtonEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.RuleSettingEnum;
import com.xbongbong.saas.enums.SignInSetEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.base.CommunicateBaseEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.help.SaasDataInitHelp;
import com.xbongbong.saas.help.SaasGetHelp;
import com.xbongbong.saas.model.CustomerCommunicateModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.SignInModel;
import com.xbongbong.saas.model.SignInSetModel;
import com.xbongbong.saas.service.SaasListService;
import com.xbongbong.saas.service.ScoreCalculateService;
import com.xbongbong.saas.service.SignInService;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.enums.DataPermissionEnum;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserModel;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author haibin.zhang
 * @version v1.0
 * @date 2019/4/1 12:23
 * @since v1.0
 */
@Service("signInService")
public class SignInServiceImpl implements SignInService {

    private static final Logger LOG = LoggerFactory.getLogger(SignInServiceImpl.class);

    @Resource
    private SignInModel signInModel;
    @Resource
    private UserModel userModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private SignInSetService signInSetService;
    @Resource
    private SaasGetHelp saasGetHelp;
    @Resource
    private SaasListService saasListService;
    @Resource
    private PushHelper pushHelper;
    @Resource
    private BaseProducer baseProducer;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private CustomerCommunicateModel customerCommunicateModel;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private PaasFormService paasFormService;
    @Resource
    private ScoreCalculateService scoreCalculateService;
    @Resource
    private SignInSetModel signInSetModel;
    @Resource
    private SignInOperationLogHandle signInOperationLogHandle;
    @Resource
    private DynamicStrategyFactory dynamicStrategyFactory;

    @Override
    public SignInExportVO exportList(SignInExportDTO signInExportDTO) throws XbbException {
        SignInDTO signInDTO = new SignInDTO();
        BeanUtil.copyProperties(signInExportDTO, signInDTO);
        signInDTO.setPage(1);
        signInDTO.setPageSize(10000);
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<SignInEntity> signInEntityList = getSignInList(signInDTO, param);
        List<SignInEntityExt> signInEntityExtList = new ArrayList<>();
        for (SignInEntity entity : signInEntityList) {
            SignInEntityExt signInEntityExt = new SignInEntityExt();
            BeanUtil.copyProperties(entity, signInEntityExt);
            signInEntityExt.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
            String formatAddress = entity.getProvince() + entity.getCity() + entity.getDistrict() + entity.getAddress();
            signInEntityExt.setFormatAddress(formatAddress);
            signInEntityExtList.add(signInEntityExt);
        }
        SignInExportVO signInExportVO = new SignInExportVO();
        signInExportVO.setSignList(signInEntityExtList);
        return signInExportVO;
    }

    @Override
    public SignInListVO list(SignInDTO signInDTO) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<SignInEntity> signInEntityList = getSignInList(signInDTO, param);
        List<SignInEntityExt> signInEntityExtList = new ArrayList<>();
        List<String> userIdIn = new ArrayList<>();
        for (SignInEntity entity : signInEntityList) {
            SignInEntityExt signInEntityExt = new SignInEntityExt();
            BeanUtil.copyProperties(entity, signInEntityExt);
            signInEntityExt.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
            String formatAddress = entity.getProvince() + entity.getCity() + entity.getDistrict() + entity.getAddress();
            signInEntityExt.setFormatAddress(formatAddress);
            signInEntityExtList.add(signInEntityExt);
            userIdIn.add(entity.getUserId());
        }
        if (!userIdIn.isEmpty()) {
            List<UserEntity> userEntityList = userModel.findEntitysByUserIds(userIdIn, signInDTO.getCorpid());
            Map<String, String> userAvatarMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (UserEntity userEntity : userEntityList) {
                userAvatarMap.put(userEntity.getUserId(), userEntity.getAvatar());
            }
            JSONArray delPerm = new JSONArray();
            delPerm.add(OperateTypeEnum.DELETE.getAlias());
            JSONArray noPerm = new JSONArray();

            boolean hasNormalPerm = signInDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.SIGN_IN_DELETE.getAlias());
            for (SignInEntityExt signInEntityExt : signInEntityExtList) {
                signInEntityExt.setUserAvatar(userAvatarMap.getOrDefault(signInEntityExt.getUserId(), ""));
                // 管理员老板，或者拥有签到删除权限的人，可以删除该签到数据
                if(signInDTO.getLoginUser().isAdminOrBoss() || hasNormalPerm){
                    signInEntityExt.setPermissionSet(delPerm);
                } else {
                    signInEntityExt.setPermissionSet(noPerm);
                }
            }
        }

        SignInListVO signInListVO = new SignInListVO();
        signInListVO.setList(signInEntityExtList);
        PageHelper pageHelper = new PageHelper(signInDTO.getPage(), signInDTO.getPageSize());
        Integer count = signInModel.getEntitysCount(param);
        pageHelper.setRowsCount(count);
        signInListVO.setPageHelper(pageHelper);
        List<ButtonPojo> topButtonList = new ArrayList<>();
        Set<String> permSet = signInDTO.getLoginUser().getPermSet();
        if (permSet.contains(ProPermissionAliasEnum.SIGN_IN_EXPORT.getAlias())) {
            ButtonPojo buttonPojo = new ButtonPojo();
            BeanUtil.copyProperties(ListTopButtonEnum.SIGNIN_EXPORT.getAnEnum(), buttonPojo);
            topButtonList.add(buttonPojo);
        }
        if (permSet.contains(ProPermissionAliasEnum.SIGN_IN_STATISTIC.getAlias())) {
            ButtonPojo buttonPojo = new ButtonPojo();
            BeanUtil.copyProperties(ListTopButtonEnum.SIGNIN_STATISTIC.getAnEnum(), buttonPojo);
            topButtonList.add(buttonPojo);
        }
        signInListVO.setTopPermissions(topButtonList);

        // 移动端签到列表 按日期分组展示
        if (Objects.equals(signInDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue())) {
            Map<String, List<SignInEntityExt>> resultMap = new LinkedHashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            signInEntityExtList.forEach(signIn -> {
                String date = DateTimeUtil.getStringEpochSecond(signIn.getAddTime(), DateTimeUtil.SDFDate);
                List<SignInEntityExt> signInList = resultMap.get(date);
                if (Objects.isNull(signInList)) {
                    signInList = new ArrayList<>();
                }
                signInList.add(signIn);
                resultMap.put(date, signInList);
            });
            signInListVO.setAppList(resultMap);
        }

        // 筛选了某个人的签到
        if (Objects.equals(signInDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue()) && Objects.nonNull(signInDTO.getCheckedUserId())) {
            try {
                UserEntity selectUser = userModel.getByKeyIngoreDel(signInDTO.getCheckedUserId(), signInDTO.getCorpid());
                // List<Long> departmentIdIn = userModel.getUserBelongDeptIdList(selectUser, true);
                List<Long> departmentIdIn = JSON.parseArray(selectUser.getDepartment(), Long.class);
                List<DepartmentEntity> departmentEntityList = departmentModel.findEntitysByDepartmentIds(departmentIdIn, signInDTO.getCorpid());
                StringBuilder departmentBuilder = new StringBuilder();
                departmentEntityList.forEach(department -> {
                    departmentBuilder.append(department.getName());
                    if (!Objects.equals(departmentEntityList.indexOf(department), departmentEntityList.size() - 1)) {
                        departmentBuilder.append(StringConstant.COMMA);
                    }
                });
                SignInListHeadVO headVO = new SignInListHeadVO(selectUser.getAvatar(), selectUser.getName(), Objects.toString(departmentBuilder), count);
                signInListVO.setSignInListHeadVO(headVO);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return signInListVO;
    }

    @Override
    public SignInStatisticVO signInStatistic(SignInStatisticDTO signInStatisticDto) throws XbbException {
        String corpid = signInStatisticDto.getCorpid();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("del", 0);
        //组织架构筛选条件处理
        setSignUserParam(signInStatisticDto, param,BasicConstant.ZERO);
        //时间筛选条件处理
        setSignTimeParam4Statistic(signInStatisticDto, param);
        // 签到人筛选
        List<String> signInPerson = signInStatisticDto.getSignInPerson();
        if (signInPerson != null && !signInPerson.isEmpty()) {
            param.put("userIdIn", signInPerson);
        }
        //分页，此处只初始化页码和每页size
        PageHelper pageHelper = new PageHelper(signInStatisticDto.getPage(), signInStatisticDto.getPageSize());
        List<Map<String, Object>> data = signInModel.getStatistic(param, pageHelper);
        PaasMenuEntity paasMenuEntity = paasMenuModel.getByAlias(XbbRefTypeEnum.SIGNIN.getAlias(), null, corpid);
        Long appId = paasMenuEntity == null ? 0 : paasMenuEntity.getAppId();
        Long menuId = paasMenuEntity == null ? 0 : paasMenuEntity.getId();
        return new SignInStatisticVO(appId, menuId, data, pageHelper);
    }

    @Override
    public SignInListVO signInCustomerList(SignInDTO signInDTO) throws XbbException {
        signInDTO.setMapList(true);
        SignInSetDetailDTO signInSetDetailDTO = new SignInSetDetailDTO();
        BeanUtil.copyProperties(signInDTO, signInSetDetailDTO);
        XbbResponse<SignInSetVO> xbbResponse = signInSetService.getSignInSet(signInSetDetailDTO);
        SignInSetVO signInSetVO = xbbResponse.getResult();
        Integer distanceType = signInSetVO.getVisibleCustomerDistance();
        SignInSetEnum.VisibleDistance visibleDistance = SignInSetEnum.VisibleDistance.getVisibleDistanceByCode(distanceType);
        NearCustomerDTO nearCustomerDTO = new NearCustomerDTO();
        BeanUtil.copyProperties(signInDTO,nearCustomerDTO);
        nearCustomerDTO.setDistancePower(visibleDistance.getDistance());
        nearCustomerDTO.setIsPublic(0);
        List<ConditionsEntityExt> conditions = new ArrayList<>();
        ConditionsEntityExt publicCondition = new ConditionsEntityExt();
        publicCondition.setAttr(CustomerManagementEnum.IS_PUBLIC.getAttr());
        publicCondition.setFieldType(CustomerManagementEnum.IS_PUBLIC.getFieldType());
        publicCondition.setSymbol(ConditionEnum.EQUAL.getSymbol());
        publicCondition.setValue(Collections.singletonList(0));
        conditions.add(publicCondition);

        nearCustomerDTO.setConditions(conditions);
        nearCustomerDTO.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
        nearCustomerDTO.setSubBusinessType(XbbRefTypeEnum.CUSTOMER.getCode());
        nearCustomerDTO.setIsNewSignIn(1);
        SearchHits hits = saasListService.getNearCustomerEsList(nearCustomerDTO);
        List<NearCustomerPojo> esList = new ArrayList<>();
        for (SearchHit hit : hits){
            PaasFormDataEntityExt entity = JSONObject.parseObject(hit.getSourceAsString(),PaasFormDataEntityExt.class);
            JSONObject data = entity.getData();
            NearCustomerPojo nearCustomerPojo = new NearCustomerPojo();
            nearCustomerPojo.setId(entity.getDataId());
            nearCustomerPojo.setName(data.getString(CustomerManagementEnum.NAME.getAttr()));
            nearCustomerPojo.mergeAddress(data.getJSONObject(CustomerManagementEnum.ADDRESS.getAttr()));
            Double distance = Double.valueOf(hit.getSortValues()[0].toString()) ;
            distance = distance == null ? -1D : distance;
            distance = distance.isInfinite() ? -1D : distance;
            nearCustomerPojo.setDistance(distance);
            if (distance >= 0 && Objects.nonNull(data.getJSONObject(CustomerManagementEnum.ADDRESS.getAttr())) && Objects.nonNull(data.getJSONObject(CustomerManagementEnum.ADDRESS.getAttr()).getJSONObject(FieldTypeEnum.LOCATION.getAlias()))){
                JSONObject latAndLon = data.getJSONObject(CustomerManagementEnum.ADDRESS.getAttr()).getJSONObject(FieldTypeEnum.LOCATION.getAlias());
                if (Objects.nonNull(latAndLon.getDouble("lat"))) {
                    nearCustomerPojo.setLatitude(latAndLon.getDouble("lat"));
                }
                if (Objects.nonNull(latAndLon.getDouble("lon"))) {
                    nearCustomerPojo.setLongitude(latAndLon.getDouble("lon"));
                }
            }
            esList.add(nearCustomerPojo);
        }

        SignInListVO signInListVO = new SignInListVO();
        signInListVO.setEsList(esList);
        PageHelper pageHelper = new PageHelper(signInDTO.getPage(), signInDTO.getPageSize());
        pageHelper.setRowsCount((int) hits.getTotalHits().value);
        signInListVO.setPageHelper(pageHelper);
        signInListVO.setTopPermissions(new ArrayList<>());

        // 可见范围设置
        signInListVO.setDistanceType(distanceType);
        signInListVO.setDistanceValue(visibleDistance.getDistance());
        signInListVO.setDistanceTypeShow(visibleDistance.getName());
        // 微调范围设置
        Integer adjustType = signInSetVO.getAdjustType();
        SignInSetEnum.AdjustType adjustTypeEnum = SignInSetEnum.AdjustType.getAdjustByCode(adjustType);
        signInListVO.setAdjustType(adjustType);
        signInListVO.setAdjustTypeValue(adjustTypeEnum.getAdjustDistance());
        signInListVO.setAdjustTypeShow(adjustTypeEnum.getName());

        return signInListVO;
    }

    @Override
    public BaseVO save(SignInSaveDTO signInSaveDTO) throws XbbException {
        SignInEntity signInEntity = new SignInEntity();
        // 签到没有地址或经纬度，不能保存
        Double longitude = signInSaveDTO.getLongitude();
        Double latitude = signInSaveDTO.getLatitude();
        boolean locationErrorFlag = Objects.isNull(longitude) || Objects.isNull(latitude);
        if (locationErrorFlag) {
            throw new XbbException(SignInErrorCodeEnum.API_ERROR_239002);
        }
        // 地址为空标识
        boolean addressErrorFlag = StringUtil.isEmpty(signInSaveDTO.getProvince()) || StringUtil.isEmpty(signInSaveDTO.getCity())
                || StringUtil.isEmpty(signInSaveDTO.getDistrict()) || StringUtil.isEmpty(signInSaveDTO.getAddress());
        if (addressErrorFlag) {
            // 由经纬度转换为地址
            JSONObject addressObj = GaodeGeoHelper.regeo(longitude, latitude);
            if (Objects.nonNull(addressObj)) {
                signInSaveDTO.setAddress(addressObj.getString(PaasConstant.ADDRESS));
                signInSaveDTO.setProvince(addressObj.getString(PaasConstant.PROVINCE));
                signInSaveDTO.setCity(addressObj.getString(PaasConstant.CITY));
                signInSaveDTO.setDistrict(addressObj.getString(PaasConstant.DISTRICT));
            }
        }

        if (StringUtil.isEmpty(signInSaveDTO.getAddress())) {
            throw new XbbException(SignInErrorCodeEnum.API_ERROR_239002);
        }

        BeanUtil.copyProperties(signInSaveDTO, signInEntity);
        if (Objects.nonNull(signInSaveDTO.getUserId())) {
            UserVO userVO = signInSaveDTO.getLoginUser();
            signInEntity.setUserName(userVO.getName());
        }
        String customerName = "";
        CustomerEntityExt customerEntityExt = null;

        SignInSetEntity entity;
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",signInSaveDTO.getCorpid());
        param.put("del", DelEnum.NORMAL.getDel());
        List<SignInSetEntity> signInSetEntityList = signInSetModel.findEntitys(param);
        if (CollectionsUtil.isEmpty(signInSetEntityList)) {
            return new BaseVO();
        }
        entity = signInSetEntityList.get(0);
        // 图片校验
        if (Objects.equals(entity.getImage(), BasicConstant.ONE)) {
            JSONArray image = JsonHelperUtil.parseArray(signInEntity.getImages());
            if (CollectionsUtil.isEmpty(image)) {
                throw new XbbException(CustomerCommunicateErrorCodeEnum.API_ERROR_206007);
            }
        }

        if (Objects.nonNull(signInSaveDTO.getCustomerId())) {
            PaasFormDataEntityExt paasFormDataEntityExt = saasGetHelp.getFormData(signInSaveDTO.getCustomerId(), signInSaveDTO.getCorpid(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
            if (Objects.nonNull(paasFormDataEntityExt)) {
                JSONObject formData = paasFormDataEntityExt.getData();
                customerName = Objects.toString(formData.getString(CustomerManagementEnum.NAME.getAttr()), "");
                signInEntity.setCustomerName(customerName);

                try {
                    customerEntityExt = new CustomerEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntityExt, customerEntityExt);

                    //新建签到中的签到时间影响客户的最后跟进时间
                    Boolean flag = paasFormService.getSingleRuleList(signInSaveDTO.getCorpid(), RuleSettingEnum.NEW_SIGN_IN_CHECK_IN_TIME.getConfig(), customerEntityExt.getFormId());
                    LOG.info("此时的签到flag为："+flag);
                    if (flag && Objects.equals(entity.getIfFollowRecords(), 1)) {
                        customerEntityExt.getData().put(CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(), DateTimeUtil.getInt());
                    }

                    if (Objects.equals(signInSaveDTO.getCustomerLocationUpdate(), 1)) {
                        JSONObject addressObj = new JSONObject();
                        addressObj.put("province", signInSaveDTO.getProvince());
                        addressObj.put("city", signInSaveDTO.getCity());
                        addressObj.put("district", signInSaveDTO.getDistrict());
                        addressObj.put("address", signInSaveDTO.getAddress());
                        JSONObject locationObj = new JSONObject();
                        locationObj.put("lat", signInSaveDTO.getLatitude());
                        locationObj.put("lon", signInSaveDTO.getLongitude());
                        addressObj.put("location", locationObj);
                        customerEntityExt.getData().put(CustomerManagementEnum.ADDRESS.getAttr(), addressObj);
                    }
                    if (Objects.nonNull(customerEntityExt.getData()) && !customerEntityExt.getData().containsKey(CustomerManagementEnum.NAME.getAttr())) {
                        LOG.info("signInServiceImpl.save not have customerName"+ JSON.toJSONString(customerEntityExt.getData()));
                    }
                    customerModel.update(customerEntityExt);
                    //评分更新（客户签到）
                    scoreCalculateService.asyncUpdateSingleDataScore(XbbRefTypeEnum.CUSTOMER_MANAGEMENT,signInSaveDTO.getCorpid(),null,customerEntityExt);
                } catch (Exception e) {
                    LOG.error("客户签到更新客户出错", e);
                }
            }
        }
        signInModel.save(signInEntity);

        // 签到后添加一条跟进记录
        if (Objects.equals(entity.getIfFollowRecords(), 1)) {
            CustomerCommunicate(signInEntity);
        }

        // 新增签到消息推送
        UserVO loginUser = signInSaveDTO.getLoginUser();
        List<String> pushUserIds = pushHelper.getUserIdListByPushSetRule(signInSaveDTO.getCorpid(), PushTypeEnum.SIGN_IN_ADD_PUSH.getCode(), PushTypeEnum.SIGN_IN_ADD_PUSH.getSubCode(),loginUser, signInEntity);
        // 58644 消息中签到打开后，提示表单无权限等问题
        PushRefTypePojo.Options options = new PushRefTypePojo.Options(signInSaveDTO.getAppId(), signInSaveDTO.getMenuId(), 0L, signInEntity.getId(), Collections.singletonList(signInEntity.getId()),SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.SIGNIN.getCode(), XbbRefTypeEnum.SIGNIN.getCode());
        String pushMsg = String.format(I18nMessageUtil.getMessage(SignInPushConstant.SIGN_IN_ADD), loginUser.getName(), customerName);
        MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(signInSaveDTO.getCorpid(), pushUserIds, Collections.singletonList(signInEntity.getId()), 0, null, I18nMessageUtil.getMessage(SignInPushConstant.SIGN_IN_ADD_TITLE), pushMsg, null, options);
        baseProducer.sendMessage(PushTypeEnum.SIGN_IN_ADD_PUSH, messageRabbitMqDTO);

        AddSignInDTO addSignInDTO = new AddSignInDTO(signInEntity,signInSaveDTO);
        signInOperationLogHandle.add(addSignInDTO);
        return new BaseVO();
    }

    @Override
    public BaseVO delete(SignInDeleteDTO signInDeleteDTO) throws XbbException {
        UserVO loginUser = signInDeleteDTO.getLoginUser();
        if (!loginUser.isAdminOrBoss() && !loginUser.getPermSet().contains(ProPermissionAliasEnum.SIGN_IN_DELETE.getAlias())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100050.getCode(), String.format(SystemErrorCodeEnum.API_ERROR_100050.getMsg(),ProPermissionAliasEnum.SIGN_IN_DELETE.getMemo()));
        }
        SignInEntity signInEntity = signInModel.getByKey(signInDeleteDTO.getSignInId(), signInDeleteDTO.getCorpid());
        if (Objects.isNull(signInEntity)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        signInModel.delete(signInDeleteDTO.getSignInId(),signInDeleteDTO.getCorpid());
        DeleteSignInDTO deleteSignInDTO = new DeleteSignInDTO(signInEntity,signInDeleteDTO);
        signInOperationLogHandle.delete(deleteSignInDTO);
        return new BaseVO();
    }

    @Override
    public SignInListVO track(SignInTrackDTO signInTrackDTO) throws XbbException {
        String checkedUserId = signInTrackDTO.getCheckedUserId();
        if (StringUtil.isEmpty(checkedUserId)) {
            checkedUserId = signInTrackDTO.getUserId();
            signInTrackDTO.setCheckedUserId(checkedUserId);
        }
        SignInDTO signInDTO = new SignInDTO();
        BeanUtil.copyProperties(signInTrackDTO, signInDTO);
        signInDTO.setPage(1);
        // 最多显示1000条轨迹
        signInDTO.setPageSize(1000);
        return list(signInDTO);
    }

    /**
     * 获取签到详情
     *
     * @param signInDetailDTO 获取详情入参
     * @return SignInDetailVO
     * @throws XbbException XbbException
     * @author GuoJun.HU
     * @date 2019/4/19 11:00
     * @since V1.0
     */
    @Override
    public SignInDetailVO detail(SignInDetailDTO signInDetailDTO) throws XbbException {
        SignInEntity entity = signInModel.getByKey(signInDetailDTO.getId(), signInDetailDTO.getCorpid());
        if (Objects.isNull(entity)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }

        SignInEntityExt signInEntityExt = new SignInEntityExt();
        BeanUtil.copyProperties(entity, signInEntityExt);
        signInEntityExt.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
        String formatAddress = entity.getProvince() + entity.getCity() + entity.getDistrict() + entity.getAddress();
        signInEntityExt.setFormatAddress(formatAddress);
        signInEntityExt.setImageArray(JsonHelperUtil.parseArray(entity.getImages()));

        String userId = entity.getUserId();
        UserEntity signInUser = userModel.getByKey(userId, signInDetailDTO.getCorpid());

        return new SignInDetailVO(signInEntityExt, signInUser);
    }

    /**
     * 获取签到列表
     *
     * @param signInDTO 列表查询入参
     * @param param     参数集合
     * @return List
     * @author GuoJun.HU
     * @date 2019/4/10 19:53
     * @since V1.0
     */
    private List<SignInEntity> getSignInList(SignInDTO signInDTO, Map<String, Object> param) throws XbbException {
        param.put("corpid", signInDTO.getCorpid());
        param.put("del", 0);
        if (Objects.isNull(signInDTO.getMapList()) || !signInDTO.getMapList()) {
            // 普通签到列表按签到时间倒序
            param.put("orderByStr", "add_time desc");
        }
        Integer page = signInDTO.getPage() == null ? 1 : signInDTO.getPage();
        Integer pageSize = signInDTO.getPageSize() == null ? 20 : signInDTO.getPageSize();
        Integer start = (page - 1) * pageSize;
        param.put("start", start);
        param.put("pageNum", signInDTO.getPageSize());

        setSignUserParam(signInDTO, param,BasicConstant.ONE);
        setSignTimeParam(signInDTO, param);
        if (signInDTO.getCommonFilter() != null){
            JSONObject commonFilter = signInDTO.getCommonFilter();
            String creator = commonFilter.getString(FieldTypeEnum.CREATORID.getAlias());
            if (StringUtil.isNotEmpty(creator)) {
                // web端签订人筛选，因为前面有分组筛选，这里用两种参数避开分组的条件
                Object userId = param.get("userId");
                if (Objects.nonNull(userId)) {
                    param.put("userIdIn", Collections.singletonList(creator));
                } else {
                    param.put("userId", creator);
                }
            }
            rangeScreen(signInDTO, commonFilter, param);
        }

        if (Objects.nonNull(signInDTO.getMapList()) && signInDTO.getMapList()) {
            // 地图签到列表
            CommentUtil.addToMap(param, "nameLike", Objects.toString(signInDTO.getNameLike(), ""));
            CommentUtil.addToMap(param, "customerNonNull", 1);
            SignInSetDetailDTO signInSetDetailDTO = new SignInSetDetailDTO();
            BeanUtil.copyProperties(signInDTO, signInSetDetailDTO);
            XbbResponse<SignInSetVO> xbbResponse = signInSetService.getSignInSet(signInSetDetailDTO);
            SignInSetVO signInSetVO = xbbResponse.getResult();
            Integer distanceType = signInSetVO.getVisibleCustomerDistance();
            setDistanceParam(param, signInDTO.getLongitude(), signInDTO.getLatitude(), distanceType);
        }
        List<SignInEntity> signInEntityList = signInModel.findEntities(param);
        Set<String> userIdInSet = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        signInEntityList.forEach(signInEntity -> {
            userIdInSet.add(signInEntity.getUserId());
        });
        Map<String, Object> userParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        userParam.put("corpid", signInDTO.getCorpid());
        userParam.put("userIdIn",userIdInSet);
        userParam.put(ParameterConstant.LEAVE_MARKS,BasicConstant.ONE);
        List<UserEntity> userEntityList = userModel.findEntitys(userParam);
        Map<String, String> userMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        userEntityList.forEach(userEntity -> {
            userMap.put(userEntity.getUserId(),userEntity.getName());
        });
        signInEntityList.forEach(signInEntity -> {
            signInEntity.setUserName(userMap.getOrDefault(signInEntity.getUserId(),signInEntity.getUserName()));
        });
        return signInEntityList;
    }

    /**
     * 设置签到人员筛选条件
     *
     * @param signInDTO 入参
     * @param param     参数集合
     * @author GuoJun.HU
     * @date 2019/4/12 15:38
     * @since V1.0
     */
    private void setSignUserParam(SignInDTO signInDTO, Map<String, Object> param,int viewPermission) {
        String checkedUserId = signInDTO.getCheckedUserId();
        String checkedDepIdStr = signInDTO.getCheckedDepId();

        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(signInDTO.getLoginUser(), userEntity);
        boolean ifBoss = Objects.equals(userModel.getDataPermission(userEntity), DataPermissionEnum.ALL.getCode());
        Integer dataPermission = userModel.getDataPermission(userEntity, SaasMarkEnum.SAAS, XbbRefTypeEnum.SIGNIN.getCode(), null);
        boolean isCompanyData = ifBoss || Objects.equals(DataPermissionEnum.ALL.getCode(), dataPermission);
        // 下属（包含自己）,todo userIdList中离职员工超过5000影响获取正常员工的获取
        List<String> userIdList = new ArrayList<>();
        if (!isCompanyData) {
            LinkedHashSet<String> userIdSet = new LinkedHashSet<>();
            // 先查在职员工，再查离职员工
            userIdList = userModel.getSubIdListByDataPermission(dataPermission, userEntity.getUserId(), userEntity.getCorpid(), BasicConstant.ZERO,false);
            userIdSet.addAll(userIdList);
            if (CollectionsUtil.isNotEmpty(userIdList) && userIdList.size() < BasicConstant.MAX_USER_COUNT) {
                List<String> twoUserIdList = userModel.getSubIdListByDataPermission(dataPermission, userEntity.getUserId(), userEntity.getCorpid(), viewPermission,false);
                userIdSet.addAll(twoUserIdList);
            }
            userIdList = new ArrayList<>(userIdSet);
            if (userIdList.size() > BasicConstant.MAX_USER_COUNT) {
                userIdList = userIdList.subList(BasicConstant.ZERO, BasicConstant.MAX_USER_COUNT);
            }
        }

        if (Objects.equals(ListGroupEnum.SIGNIN_RESPONSIBLE.getCode(), signInDTO.getListGroupId())) {
            // 我的
            param.put("userId", signInDTO.getUserId());
        } else if (StringUtil.isNotEmpty(checkedUserId)) {
            // 筛选某个人
            param.put("userId", "-1");
            if (isCompanyData || userIdList.contains(checkedUserId)) {
                param.put("userId", checkedUserId);
            }
        } else if (Objects.equals(ListGroupEnum.SIGNIN_RESPONSIBLE_SUB.getCode(), signInDTO.getListGroupId())) {
            // 下属
            if (isCompanyData) {
                param.put("userIdNotIn", Collections.singletonList(signInDTO.getUserId()));
                return;
            }
            if (userIdList.isEmpty()) {
                userIdList.add("-1");
            }
            // 移除自己
            userIdList.remove(userEntity.getUserId());
            param.put("userIdIn", userIdList);
        } else if (StringUtil.isNotEmpty(checkedDepIdStr)) {
            // 筛选部门
            Long checkedDepId = Long.parseLong(checkedDepIdStr);
            if (Objects.equals(checkedDepId,PaasConstant.CORP_DEPARTMENT_ID)){
                if (isCompanyData) {
                    return;
                }
            } else {
                List<String> depUserIdList = userModel.getUserIdsRecursionDep(Collections.singletonList(checkedDepId),signInDTO.getCorpid());
                userIdList = isCompanyData ? depUserIdList : userIdList;
                userIdList.retainAll(depUserIdList);
            }
            if (userIdList.isEmpty()) {
                userIdList.add("-1");
            }
            param.put("userIdIn", userIdList);
        } else {
            if (isCompanyData) {
                return;
            }
            if (userIdList.isEmpty()) {
                userIdList.add("-1");
            }
            param.put("userIdIn", userIdList);
        }
    }

    /**
     * 设置时间筛选参数
     *
     * @param signInDTO 入参
     * @param param     参数集合
     * @throws
     * @author GuoJun.HU
     * @date 2019/4/12 15:14
     * @since V1.0
     * @update 2019/6/17 10:31 by zcp 自定义时间筛选处理错误更改
     */
    private void setSignTimeParam(SignInDTO signInDTO, Map<String, Object> param) throws XbbException {
        JSONArray signTime = signInDTO.getSignInTime();
        if (!(Objects.isNull(signTime) || signTime.isEmpty())) {
            param.put("startAddTime", DateTimeUtil.getInt(signTime.getString(0), DateTimeUtil.SDFDate));
            param.put("endAddTime", DateTimeUtil.getInt(signTime.getString(1), DateTimeUtil.SDFDate) + TimeConstant.SECONDS_PER_DAY);
        } else {
            if (StringUtil.isNotEmpty(signInDTO.getStartTime())) {
                param.put("startAddTime", DateTimeUtil.getInt(signInDTO.getStartTime(), DateTimeUtil.SDFDate));
            }
            if (StringUtil.isNotEmpty(signInDTO.getEndTime())) {
                param.put("endAddTime", DateTimeUtil.getInt(signInDTO.getEndTime(), DateTimeUtil.SDFDate) + TimeConstant.SECONDS_PER_DAY);
            }
        }
    }

    /**
     * 设置统计时间筛选参数
     * @param signInStatisticDto 统计入参
     * @param param 参数集合
     * @throws XbbException
     * @author zcp
     * @date 2019/6/17 20:37
     * @since v1.0
     * @version v1.0
     */
    private void setSignTimeParam4Statistic(SignInStatisticDTO signInStatisticDto, Map<String, Object> param) throws XbbException {
        FiscalYearTimePojo fiscalYearTimePojo = signInStatisticDto.getTimeFilter();
        String startTime = fiscalYearTimePojo.getStartTime();
        String endTime = fiscalYearTimePojo.getEndTime();
        if (StringUtil.isNotEmpty(startTime) || StringUtil.isNotEmpty(endTime)) {
            if (StringUtil.isNotEmpty(startTime)) {
                param.put("startAddTime", DateTimeUtil.getInt(startTime, DateTimeUtil.SDFDate));
            }
            if (StringUtil.isNotEmpty(endTime)) {
                param.put("endAddTime", DateTimeUtil.getInt(endTime, DateTimeUtil.SDFDate) + TimeConstant.SECONDS_PER_DAY);
            }
        } else {
            Integer timeType = fiscalYearTimePojo.getTimeType();
            if (Objects.nonNull(timeType)) {
                Integer startAddTime = FiscalYearHelp.getStartTime(fiscalYearTimePojo, timeType, 1);
                Integer endAddTime = FiscalYearHelp.getEndTime(fiscalYearTimePojo, startAddTime, timeType, 1);
                param.put("startAddTime", startAddTime);
                param.put("endAddTime", endAddTime);
            }
        }
    }

    /**
     * 设置 经纬度 筛选条件
     *
     * @param modelMap     查询条件
     * @param lon          精度
     * @param lat          维度
     * @param distanceType 可见范围 {@link com.xbongbong.saas.enums.SignInSetEnum.VisibleDistance}
     * @author zheng.li
     * @time 2017-2-24 下午2:23:33
     */
    private void setDistanceParam(Map<String, Object> modelMap, Double lon, Double lat, Integer distanceType) {
        if (distanceType != null) {
            Integer distancePower;
            switch (distanceType) {
                case 1:
                    distancePower = 500;
                    break;
                case 2:
                    distancePower = 1000;
                    break;
                case 3:
                    distancePower = 1500;
                    break;
                case 4:
                    distancePower = 3000;
                    break;
                case 5:
                    distancePower = null;
                    break;
                default:
                    distancePower = null;
                    break;
            }
            if (lon <= 180 && lat <= 90 && distancePower != null) {
                CommentUtil.addToMap(modelMap, "lat", lat);
                CommentUtil.addToMap(modelMap, "lng", lon);
                CommentUtil.addToMap(modelMap, "distancePower", distancePower);
            }
        }
    }

    /**
     * 签到后添加一条跟进记录
     *
     * @param signInEntity 签到实体
     * @return
     * @throws
     * @author xingxing.xiao
     * @date 2019/07/03 15:27
     */
    private void CustomerCommunicate(SignInEntity signInEntity) throws XbbException {
        // 以下代码参考 web 端新建客户跟进记录方法中的部分逻辑
        String corpid = signInEntity.getCorpid();
        String userId = signInEntity.getUserId();

        // 'data' 字段是json类型，属性是 CommunicateBaseEnum.java 的枚举 (注：MySQL 5.7 后支持json里面字段的查询)
        JSONObject data = new JSONObject();
        data.put(CustomerCommunicateEnum.CUSTOMER_NAME.getAttr(), signInEntity.getCustomerId());
        data.put(CustomerCommunicateEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), signInEntity.getCustomerName());
        data.put(CustomerCommunicateEnum.AUTO_GEN.getAttr(), 0);
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        data.put(CustomerCommunicateEnum.USER_ID.getAttr(), userEntity.getUserId());
        data.put(CustomerCommunicateEnum.USER_NAME.getAttr(), userEntity.getName());
        data.put(CustomerCommunicateEnum.USER_AVATAR.getAttr(), Collections.singletonList(userEntity.getAvatar()));
        // 跟进方式默认为 1：当面拜访
        data.put(CommunicateBaseEnum.TYPE.getAttr(), 1);
        String images = signInEntity.getImages();
        if (StringUtil.isNotEmpty(images)) {
            try {
                JSONArray image = JSONArray.parseArray(images);
                data.put(CommunicateBaseEnum.IMAGE.getAttr(), image);
            } catch (Exception e) {
                LOG.info("客户跟进记录图片地址解析出错：" + images);
            }
        }
        //data.put(CommunicateBaseEnum.IMAGE.getAttr(), signInEntity.getImages());
        data.put(CommunicateBaseEnum.MEMO.getAttr(), signInEntity.getMemo());
        // 地址要做处理，参考app端跟进记录位置 "geo_1":{"address":"滨盛路1495号靠近天恒大厦","province":"浙江省","city":"杭州市","district":"滨江区","location":{"lat":30.212653,"lng":120.212581}}
        JSONObject addressData = new JSONObject();
        addressData.put(AddressEnum.ADDRESS.getAlias(), signInEntity.getAddress());
        addressData.put(AddressEnum.PROVINCE.getAlias(), signInEntity.getProvince());
        addressData.put(AddressEnum.CITY.getAlias(), signInEntity.getCity());
        addressData.put(AddressEnum.DISTRICT.getAlias(), signInEntity.getDistrict());
        // 经纬度判断
        Double latitude = signInEntity.getLatitude();
        Double longitude = signInEntity.getLongitude();
        if (Objects.nonNull(latitude) && Objects.nonNull(longitude) && longitude <= PaasConstant.LONGITUDE_MAX && latitude <= PaasConstant.LATITUDE_MAX) {
            JSONObject location = new JSONObject();
            location.put("lat", signInEntity.getLatitude());
            location.put("lon", signInEntity.getLongitude());
            addressData.put("location", location);
        }
        data.put(CommunicateBaseEnum.ADDRESS.getAttr(), addressData);
        // 给定一些默认值
        for (Map.Entry<String,Object> entry : SaasDataInitHelp.initCustomerCommunicate().entrySet()){
            SaasDataInitHelp.antDataSet(data, entry.getKey(), entry.getValue());
        }

        CustomerCommunicateEntityExt communicateEntity = new CustomerCommunicateEntityExt();
        communicateEntity.setData(data);
        communicateEntity.setCorpid(corpid);
        // 根据 business_type 去 tb_paas_form 表中查询一条记录
        PaasFormEntity paasFormEntity = paasFormModel.getByBusinessType(XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode(), corpid);
        communicateEntity.setAppId(paasFormEntity.getAppId());
        communicateEntity.setMenuId(paasFormEntity.getMenuId());
        communicateEntity.setFormId(paasFormEntity.getId());
        communicateEntity.setSerialNo("");
        communicateEntity.setOwnerId(userId);
        communicateEntity.setDepartmentId(0L);
        // 流程状态枚举值
        communicateEntity.setFlowStatus(FlowStatusEnum.NOT_NEED_APPROVAL.getType());
        // 项目日志类型 （0：跟进记录，其他：见枚举）
        communicateEntity.setLogType(0);
        communicateEntity.setCreatorId(userId);
        communicateEntity.setDel(0);
        customerCommunicateModel.insert(communicateEntity);

        CommunicateDynamicStrategy communicateDynamicStrategy = dynamicStrategyFactory.getCommunicateDynamicStrategyByBusinessType(XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode());
        SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
        BeanUtil.copyProperties(signInEntity, saasFormSaveDTO);
        saasFormSaveDTO.setBusinessType(XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode());
        saasFormSaveDTO.setNewPaasFormDataEntity(communicateEntity);
        communicateDynamicStrategy.save(DynamicSaveDTO.initDynamicSaveDTO(null, null, saasFormSaveDTO, userEntity, null));
    }

    /**
     * 设置范围筛选
     *
     * @param signInDTO
     * @param commonFilter
     * @param param
     * @throws XbbException
     * @author long.rao
     * @date 2020-03-03 15:13
     */
    private void rangeScreen(SignInDTO signInDTO, JSONObject commonFilter, Map<String, Object> param) throws XbbException {
        if (Objects.equals(signInDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue())) {
            return;
        }
        JSONObject rangeScreen = commonFilter.getJSONObject(RangeScreenConstant.RANGE_SCREEN);
        if (Objects.isNull(rangeScreen) || Objects.isNull(rangeScreen.get(RangeScreenConstant.TYPE)) || StringUtil.isEmpty(rangeScreen.getString(RangeScreenConstant.TYPE)) || Objects.isNull(rangeScreen.get(RangeScreenConstant.VALUE))) {
            return;
        }

        String type;
        List<String> values;
        try {
            type = rangeScreen.getString(RangeScreenConstant.TYPE);
            values = rangeScreen.getJSONArray(RangeScreenConstant.VALUE).toJavaList(String.class);
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), "signinserviceimpl.getSignInList中的commonFilter参数错误");
        }
        if (CollectionsUtil.isEmpty(values)) {
            return;
        }
        if (Objects.equals(type, RangeScreenConstant.DEPARTMENT)) {
            List<Long> deptIds = new ArrayList<>(values.size());
            values.forEach(item -> deptIds.add(Long.valueOf(item)));
            values = userModel.getUserIdsRecursionDep(deptIds, signInDTO.getCorpid(), 1, true);
        }
        param.put("userIdIn", values);
    }
}
